package com.zzzyh.blogbyspring.controller;

import com.zzzyh.blogbyspring.pojo.UserInfo;
import com.zzzyh.blogbyspring.service.UserService;
import com.zzzyh.blogbyspring.utils.JwtUtils;
import com.zzzyh.blogbyspring.utils.MD5SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class Login {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(@RequestBody UserInfo userInfo){
        log.info("userInfo:{}",userInfo);
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUserName())
                || !StringUtils.hasLength(userInfo.getPassword()))
            return "用户名或密码不能为空";
        UserInfo user = userService.getUserInfoByUserName(userInfo.getUserName());
        if(user == null)
            return "用户不存在";
        if(!MD5SecurityUtils.verify(userInfo.getPassword(), user.getPassword()))
            return "密码错误";
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("userName", userInfo.getUserName());
        return JwtUtils.getToken(map);
    }
}
